#include <iostream>
#include <pthread.h>
#include <cstdlib>
#include <time.h>
#include <unistd.h>
#include "RingQueue.hpp"

// 生产者
void* producer(void* args)
{
    RingQueue<int>* rq = (RingQueue<int>*) args;
    while (true)
    {
        int num = rand() % 99 + 1;
        rq->push(num);
        std::cout << "生产者" << pthread_self() << " 生产数据:" << num << std::endl;
    }
    return nullptr;
}

// 消费者
void* consumer(void* args)
{
    RingQueue<int>* rq = (RingQueue<int>*) args;
    while (true)
    {
        sleep(1);
        int num;
        rq->pop(&num);
        std::cout << "消费者" << pthread_self() << " 取得数据:" << num << std::endl;
    }
    return nullptr;
}

int main()
{
    srand((unsigned int)time(nullptr) ^ getpid());
    RingQueue<int>* rq = new RingQueue<int>;
    pthread_t ptid[4];
    pthread_t ctid[2];

    pthread_create(ptid, nullptr, producer, (void*)rq);
    pthread_create(ptid + 1, nullptr, producer, (void*)rq);
    pthread_create(ptid + 2, nullptr, producer, (void*)rq);
    pthread_create(ptid + 3, nullptr, producer, (void*)rq);

    pthread_create(ctid, nullptr, consumer, (void*)rq);
    pthread_create(ctid + 1, nullptr, consumer, (void*)rq);


    for (int i = 0; i < 4; ++i) pthread_join(ptid[i], nullptr);
    for (int j = 0; j < 2; ++j) pthread_join(ctid[j], nullptr);

    delete rq;
    return 0;
}